<?php

require_once("../services/Connection.class.php");

//echo "<h1>Payment return</h1>";

$orderno = $_SESSION["ss_last_orderno"];
$ppAcc = "petrs_1312314665_biz@fibix.org"; //PayPal account email
$at = "HdkxdMb5_8rJORjcxILqpPYuKRQCmU9WWXPPrRp5pF_rtIKHff2qMiJ2Sq4"; //PDT Identity Token
$url = "https://www.sandbox.paypal.com/cgi-bin/webscr"; //Test
//$url = "https://www.paypal.com/cgi-bin/webscr"; //Live
$tx = $_REQUEST["tx"]; //this value is return by PayPal
$cmd = "_notify-synch";
//$post = "tx=$tx&at=$at&amp;cmd=$cmd";
  $post = "tx=$tx&at=$at&cmd=$cmd";

//Send request to PayPal server using CURL
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);

$result = curl_exec ($ch); //returned result is key-value pair string
$error = curl_error($ch);

if (curl_errno($ch) != 0) //CURL error
	exit("ERROR: Failed updating order. PayPal PDT service failed.");

	
$longstr = str_replace("\r", "", $result);
$lines = split("\n", $longstr);

//parse the result string and store information to array
if ($lines[0] == "SUCCESS") 
{
	//successful payment
	$ppInfo = array();
	for ($i=1; $i<count($lines); $i++) 
	{
		$parts = split("=", $lines[$i]);
		if (count($parts)==2) 
		{
			$ppInfo[$parts[0]] = urldecode($parts[1]);
		}
	}
	/*
	$curtime = gmdate("d/m/Y H:i:s");
	//capture the PayPal returned information as order remarks
	$oremarks =
	'PayPal Transaction Information...<br>'.
	'Txn Id: '.$ppInfo['txn_id'].'<br>'.
	'Txn Type: '.$ppInfo['txn_type'].'<br>'.
	'Item Number: '.$ppInfo['item_number'].'<br>'.
	'Payment Date: '.$ppInfo['payment_date'].'<br>'.
	'Payment Type: '.$ppInfo['payment_type'].'<br>'.
	'Payment Status: '.$ppInfo['payment_status'].'<br>'.
	'Currency: '.$ppInfo['mc_currency'].'<br>'.
	'Payment Gross: '.$ppInfo['payment_gross'].'<br>'.
	'Payment Fee: '.$ppInfo['payment_fee'].'<br>'.
	'Payer Email: '.$ppInfo['payer_email'].'<br>'.
	'Payer Id: '.$ppInfo['payer_id'].'<br>'.
	'Payer Name: '.$ppInfo['first_name'].' '.$ppInfo['last_name'].'<br>'.
	'Payer Status: '.$ppInfo['payer_status'].'<br>'.
	'Country: '.$ppInfo['residence_country'].'<br>'.
	'Business: '.$ppInfo['business'].'<br>'.
	'Receiver Email: '.$ppInfo['receiver_email'].'<br>'.
	'Buy option: '.$ppInfo['option_selection1'].'<br>'.
	'Receiver Id: '.$ppInfo['receiver_id'].'<br>';

	foreach($ppInfo as $key=>$value)
	{
		echo "\$key = ".$key." and \$value = ".$value;
	}
	*/
	//echo $oremarks;

	//Update database using $orderno, set status to Paid
	//Send confirmation email to buyer and notification email to merchant

	$database = new Connection();

	$generatedKey = sha1(mt_rand(10000,99999).time().$ppInfo['payer_email']);
		
		$query = "INSERT INTO  fibix_orders (  TxnID,  TxnType, ItemNumber, PaymentDate, PaymentType, PaymentStatus, Currency, PayerEmail, PayerID, PayerName , PayerStatus , Country, BuyOption, GeneratedKey) VALUES (" .
	 "'" . $ppInfo['txn_id']. "','" . $ppInfo['txn_type'] . "', '" .  $ppInfo['item_number'] . "',  '" .$ppInfo['payment_date'] ."'  , '" .  $ppInfo['payment_type']."', '"
	 . $ppInfo['payment_status'] ."', '" . $ppInfo['mc_currency']. "', '". $ppInfo['payer_email']."', '" .$ppInfo['payer_id']."', '". $ppInfo['first_name'].' '.$ppInfo['last_name'] ."', '"
	 . $ppInfo['payer_status'] ."', '" . $ppInfo['residence_country'] ."', '" .$ppInfo['option_selection1']. "', '". $generatedKey.   "') ";   
	 
	// echo '<br><br>';
//	 echo $query;
	 
		$result = $database->runQuery($query); 

		//echo '<br><br>';
		//echo $result;
		
	//Send email with activation key to the user
	 //$to =  $ppInfo['payer_email'];
	 $to =  'mikrogen@gmail.com';
	 $subject = "Fibix user registration code";
	 $body = "Hello ". $ppInfo['first_name'].' '.$ppInfo['last_name'] .",\n\nthank You for your registration as ".$ppInfo['option_selection1']. ".\n\n".
	 "Your registration code is " . $generatedKey . " \n\n". 
	 "Keep it to proove your registration if needed. To finish registration, submit this code in Fibix editor, Help->Submit registration code\n\n".
	 "Best regards\nFibix studio team";
	 
	 $headers = 'From: info@fibix.org' . "\r\n" .
    'Reply-To: info@fibix.org' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
	
	
	 if (mail($to, $subject, $body, $headers)) 
	 {
		//echo("<p>Message successfully sent!</p>");
	} else 
	{
	//	echo("<p>Message delivery failed...</p>");
	}
	


	//Send email to us to be informed
	 $to =  'info@fibix.org';
	 //$to =  'mikrogen@gmail.com';
	 $subject = "We have payment! (".$ppInfo['option_selection1'].") from ". $ppInfo['payer_email'];
	 $body = "";
	foreach($ppInfo as $key=>$value)
	{
		$body = $body . $key." = ".$value. "\n";
	}

	$body = $body . "\n\nHis registration code is " . $generatedKey . " \n\n";
	
	$body = $body . "Hurray :)";
	 
	 if (mail($to, $subject, $body, $headers)) 
	 {
		//echo("<p>Message successfully sent!</p>");
	} else 
	{
	//	echo("<p>Message delivery failed...</p>");
	}
	
	
	
	echo '<META HTTP-EQUIV="Refresh" Content="0; URL=paypal_success.php">';	
	exit;
//Redirect to thankyou page
}
//Payment failed
else {
//Delete order information
//Redirect to failed page
	echo '<META HTTP-EQUIV="Refresh" Content="0; URL=paypal_cancel.php">';	
}

?>